
require 'ruby_gems'
require 'mongrel'

require 'appwiki/base/base_request.rb'

@@testlock = Mutex.new

#
#  a request abstraction
#

class BaseRequestMongrel < BaseRequest

    ##########################################################################
    # init
    ##########################################################################

    def initialize(request,response)

      #@status = 200
      #@method = (@env['REQUEST_METHOD']||'GET').downcase
      #@cookies
      #@params
      parse(request.body,request.params)

      @referer = @env['REFERER'] if !@referer
      @referer = @env['HTTP_REFERER'] if !@referer
      @content_type = 'text/html'

      @host = @env['SERVER_NAME']
      #@host = @@sethostname if @@sethostname
      @path = @env['REQUEST_PATH']
      @path = "" if !@path
      @request_uri = self

      @request = request
      @response = response
      @headers_out = H.new 

    end

    def set_redirect(value)
      @response.start(303) do |head,out|
        head['Location'] = value
        out.write ""
      end
    end

    def set_content_type(value)
      @content_type = value
    end

    def set_body(body)
      raise "something is horribly wrong" if !@host || !@cookies || !@response
      domainbase = @host.split('.')[-2..-1].join('.')
      cookies = @cookies.map { |k,v|
         "#{k}=#{escape(v)};Domain=.#{domainbase};Path=/" if v != @k[k] 
      }.compact
      @response.start(200) do |head,out|
        head['Content-Type'] = @content_type
        #head['Content-Length'] = body.length if body  # done for us
        #head['connection'] = 'close'  # done for us
        #head['expires'] = Time.now
        head['Cache-Control'] = 'no-cache'
        head['Pragma'] = 'no-cache'
        head['Expires'] = '-1'
        head['Set-Cookie'] = cookies
        out.write body
      end
    end

    def set_cookies
    end

    def []=(a,b)
      @headers_out[a] = b
    end

    def [](a) 
      @headers_out[a]
    end

    def method_missing(m,*a)
      logmsg "base_mongrel: method not found!!! #{m}"
      exit
    end

end

#
# mongrel event handler  / server abstraction for appwiki
#
class BaseServer < Mongrel::HttpHandler
  def initialize
    #@guard = Mutex.new
    #@klass = klass
  end
  def process(request, response)
    return if response.socket.closed?
     # xxx we need this due to activerecord collision - fix
    @@testlock.synchronize do
      req = BaseRequestMongrel.new request, response
      @@routes.each do |route|
        return true if route.resolve(req,req,nil)
      end
    end
  end
  def self.run
    h = Mongrel::HttpServer.new("#{@@server_ip}", "#{@@server_port}")
    h.register("/", BaseMongrelHandler.new)
    h.run.join
  end
end
